package com.fr.data.impl.sap;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import com.fr.data.AbstractDataModel;
import com.fr.general.GeneralUtils;
import com.fr.general.data.TableDataException;
import com.fr.stable.StableUtils;

public class SimpleGeneralQuerySAPDataModel extends AbstractDataModel {
	private String connectionName;
    private String tableName;
    private String[] selectClaus;
    private String[] whereClaus;
    private List data = null;
    private static final int JDK5 = 5;

	public SimpleGeneralQuerySAPDataModel(String connectionName,
			String tableName, String[] selectClaus, String[] whereClaus) {
		this.connectionName = connectionName;
		this.tableName = tableName;
		this.selectClaus = selectClaus;
		this.whereClaus = whereClaus;
	}

	public int getColumnCount() throws TableDataException {
		return selectClaus == null ? 0 : selectClaus.length;
	}

	public String getColumnName(int columnIndex) throws TableDataException {
		return selectClaus == null ? null : selectClaus[columnIndex];
	}

	public int getRowCount() throws TableDataException {
		initData();
		return data.size();
	}

	public Object getValueAt(int rowIndex, int columnIndex)
			throws TableDataException {
		initData();
		return columnIndex < 0 ? null : (hasRow(rowIndex) ? ((Object[])data.get(rowIndex))[columnIndex] : null);
	}
	
	private void initData() throws TableDataException {
		if (data == null) {
			data = new ArrayList();
			try {
                if(StableUtils.getMajorJavaVersion() < JDK5){
				SAPUtils.getTransparentTable(connectionName, tableName, whereClaus, selectClaus, data);
                }else{
                    Class SAPUtilsJDK5Class;
                    SAPUtilsJDK5Class = GeneralUtils.classForName("com.fr.data.impl.sap.SAPUtilsJDK5");
                    Method method = SAPUtilsJDK5Class.getMethod("getTransparentTable",new Class[]{
                            String.class,
                            String.class,
                            String[].class,
                            String[].class,
                            List.class
                    });
                    method.invoke(SAPUtilsJDK5Class,new Object[]{
                            connectionName,
                            tableName,
                            whereClaus,
                            selectClaus,
                            data
                    });
                }
			} catch (Exception e) {
				throw new TableDataException(e.getMessage(), e);
			}
		}
	}

	public void release() throws Exception {
		if (data != null) {
			data.clear();
			data = null;
		}
	}
}
